import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
import { observer } from 'mobx-react';

import ContentLayout from '@/component/common/ContentLayout';
import houseModeStyle from './houseMode.scss';

import { Input, Select, Form } from 'antd';
import HouseInfoModal from '@/component/house/HouseInfoModal';

import HeaderNavStore from '@/store/HeaderNav';
import HouseModeSkinStore from '@/store/HouseModeSkin';
import adminType from '@/tool/adminType';

import ApiHelper from '@/store/ApiHelper';
import { house_mode as api_house_mode } from '@/constants/ApiTypes';

import { API_URL } from '@/config';

const Search = Input.Search;
const FormItem = Form.Item;
const Option = Select.Option;

import StoreListMini from '@/store/StoreListMini';
import BrokerListMini from '@/store/BrokerListMini';

class HouseItem extends Component {
    static propTypes = {
        onClick: PropTypes.func,
        houseData: PropTypes.object.isRequired
    };
    onClick = () => {
        console.log(this.props.houseData)
        if (typeof this.props.onClick == 'function') this.props.onClick();
    };
    render() {
        const { houseData } = this.props;
        let stateIcons = [];
        if (houseData.vacant) {
            stateIcons =
                <div className={houseModeStyle['state-item']}>
                    <i className={houseModeStyle['icon-kong']}>空</i><span className={houseModeStyle['house-item-state-desc']}>{houseData.vacant}</span>
                </div>;
        } else {
            if (houseData.overdue) {
                stateIcons.push(
                    <div key="icon-yu" className={houseModeStyle['state-item']}>
                        <i className={houseModeStyle['icon-yu']}>逾</i><span className={houseModeStyle['house-item-state-desc']}>{houseData.overdue}</span>
                    </div>
                );
            }
            if (houseData.arrears) {
                stateIcons.push(
                    <div key="icon-fei" className={houseModeStyle['state-item']}>
                        <i className={houseModeStyle['icon-fei']}>费</i><span className={houseModeStyle['house-item-state-desc']} style={{ visibility: 'hidden' }}>0</span>
                    </div>
                );
            }
            if (houseData.loss && stateIcons.length < 2) {
                stateIcons.push(
                    <div key="icon-kui" className={houseModeStyle['state-item']}>
                        <i className={houseModeStyle['icon-kui']}>亏</i><span className={houseModeStyle['house-item-state-desc']}  style={{ visibility: 'hidden' }}>0</span>
                    </div>
                );
            }
        }
        return (
            <div className={houseModeStyle['house-item']} onClick={this.onClick}>
                <div className={houseModeStyle['house-item-name']} title={`${houseData.address_detail}`}>{houseData.address_detail}</div>
                <div className={houseModeStyle['house-item-rent']}>
                    <span className={houseModeStyle['house-item-rent-amount']}>￥{houseData.rent / 100}元</span><span className={houseModeStyle['house-item-renter']}>{houseData.broker_name}</span>
                </div>
                <div className={houseModeStyle['house-item-state']}>
                    {stateIcons}
                </div>
                {!!houseData.lock && <div className={houseModeStyle['house-item-lock']} ><img src="/static/alliance2/image/house/lock-white.png" /></div>}
            </div>
        );
    }
}

@observer class HouseMode extends Component {
    state = {
        loading: true,
        houseInfoModalVisible: false,
        houseList: [],
        sum: {},
        store_id: '',
        broker_name: '',
        kword: '',
        query: {},
        houseInfoModalProps: {
            itemInfo: {}
        }
    };
    async componentDidMount() {
        this._isMounted = true;
        HeaderNavStore.addHouseModeNav();
        const result = await this.requestHouseList();
        if (!result.status) return;
        const store_result = await StoreListMini.getInfo();
        if (!store_result) return;
        this._setState({
            loading: false,
            houseList: result.info.house_list,
            sum: result.info.sum
        });
    }
    componentWillUnmount() {
        this._isMounted = false;
        HeaderNavStore.removeAllExtra();
    }
    //fix异步
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
    requestHouseList = () => {
        let { query, store_id, broker_name, kword } = this.state;
        let data = { ...query };
        if (kword !== '') data.kword = kword;
        if (store_id !== '') data.store_id = store_id;
        if (broker_name !== '') data.broker_name = broker_name;
        return ApiHelper.requestPost(api_house_mode, data);
    };
    searchHouseList = async () => {
        const result = await this.requestHouseList();
        if (!result.status) return;
        this._setState({
            loading: false,
            houseList: result.info.house_list,
            sum: result.info.sum
        });
    };
    closeHouseInfoModal = (refresh = false) => {
        if (refresh) this.searchHouseList();
        this.setState({ houseInfoModalVisible: false });
    };
    showHouseInfoModal = itemInfo => {
        this.setState({
            houseInfoModalVisible: true,
            houseInfoModalProps: {
                itemInfo
            }
        });
    };
    selectStore = value => {
        this._setState({
            store_id: value,
            broker_name: ''
        });
        if (value == '') {
            return BrokerListMini.info.clear();
        }
        BrokerListMini.getInfo(value);
    };
    selectBroker = value => {
        this._setState({
            broker_name: value
        });
    };
    clickFilter = e => {
        const name = e.target.name;
        let { query } = this.state;
        if (query[name]) {
            delete query[name];
        } else {
            query[name] = 1;
        }
        this._setState({ query });
    };
    searchInputChange = e => {
        this._setState({ kword: e.target.value });
    };
    render() {
        const { houseInfoModalVisible, houseList, sum, query, houseInfoModalProps } = this.state;
        const { closeHouseInfoModal, showHouseInfoModal, clickFilter } = this;
        const skinName = HouseModeSkinStore.skin;
        const houseItemList = houseList.map((val, index) => <HouseItem key={val.house_no} houseData={val} onClick={() => showHouseInfoModal(val)} />);
        const storeListMini = StoreListMini.info;
        const brokerListMini = BrokerListMini.info;
        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = brokerListMini.map((val, index) => {
            return <Option key={index} value={`${val.realname}`}>{val.realname}</Option>;
        });
        const filterStyle = houseModeStyle['selected'];
        return (
            <ContentLayout navTitle="房源" loading={this.state.loading}>
                <div className={houseModeStyle['house-mode-wrap']}>
                    <div className={houseModeStyle['house-list-wrap'] + ` ${houseModeStyle[skinName]}`}>
                        <div className={houseModeStyle['house-mode-nav']}>
                            <NavLink exact to="/房源" activeClassName={houseModeStyle['active']}>房源模式</NavLink>
                            <NavLink exact to="/房源/房源列表" activeClassName={houseModeStyle['active']}>房源列表</NavLink>
                        </div>
                        <div className={houseModeStyle['house-list']}>
                            {houseItemList}
                        </div>
                    </div>
                    <HouseInfoModal visible={houseInfoModalVisible} onClose={closeHouseInfoModal} {...houseInfoModalProps} />
                    <div className={houseModeStyle['operator-wrap']}>
                        <div className={houseModeStyle['filter-wrap']}>
                            <Form layout="inline">
                                <div className={houseModeStyle['filter-search']}>
                                    <Search
                                        placeholder="搜索区域/小区/栋座/门牌号/姓名"
                                        value={this.state.kword}
                                        onPressEnter={this.searchHouseList}
                                        onChange={this.searchInputChange}
                                        onSearch={this.searchHouseList}
                                    />
                                </div>
                                <div className={houseModeStyle['filter-other']}>
                                    {adminType() == 1 &&
                                    <FormItem label="门店">
                                        <Select placeholder="选择门店"
                                            style={{ width: 130 }} value={this.state.store_id} defaultValue="" onChange={this.selectStore}>
                                            <Option key="default" value="">不限</Option>
                                            {storeOptionList}
                                        </Select>
                                    </FormItem>}
                                    <FormItem label="经纪人" className={houseModeStyle['form-item']}>
                                        <Select placeholder="选择经纪人"
                                            defaultValue="" value={this.state.broker_name} style={{ width: 100 }} onChange={this.selectBroker}>
                                            <Option key="default" value="">不限</Option>
                                            {brokerOptionList}
                                        </Select>
                                    </FormItem>
                                    <div className={houseModeStyle['filter-key-group']}>
                                        <a name="arrears" href="javascript:void(0);" className={query.arrears ? filterStyle : null} onClick={clickFilter}>欠费</a>
                                        <a name="overdue" href="javascript:void(0);" className={query.overdue ? filterStyle : null} onClick={clickFilter}>逾期</a>
                                        <a name="stages" href="javascript:void(0);" className={query.stages ? filterStyle : null} onClick={clickFilter}>分期</a>
                                        <a name="vacant" href="javascript:void(0);" className={query.vacant ? filterStyle : null} onClick={clickFilter}>空置</a>
                                        <a name="lock" href="javascript:void(0);" className={query.lock ? filterStyle : null} onClick={clickFilter}>智能锁</a>
                                        <a href="javascript:void(0);" className={houseModeStyle['search']} onClick={this.searchHouseList}>查询</a>
                                    </div>
                                </div>
                            </Form>
                        </div>
                        <div className={houseModeStyle['legend-wrap']}>
                            <div className={houseModeStyle['legend-item']}>
                                <span><i className={houseModeStyle['icon-fei']}>费</i>租客欠费</span>
                                <span><i className={houseModeStyle['icon-kui']}>亏</i>房源亏损</span>
                            </div>
                            <div className={houseModeStyle['legend-item']}>
                                <span><i className={houseModeStyle['icon-kong']}>空</i>无人入住</span>
                                <span><i className={houseModeStyle['icon-yu']}>逾</i>缴费逾期</span>
                            </div>
                            <div className={houseModeStyle['legend-item']}>
                                <span><i className={houseModeStyle['icon-suo']}><img src="/static/alliance2/image/house/lock-white.png" /></i>已安装智能锁</span>
                            </div>
                        </div>
                        <div className={houseModeStyle['count-wrap']}>
                            <p><span className={houseModeStyle['count-label']}>普通房源：</span>{sum.nverify_count + sum.verify_count}套</p>
                            <p><span className={houseModeStyle['count-label']}>认证房源：</span>{sum.verify_count}套</p>
                            <div className={houseModeStyle['count-item-group']}>
                                <p><span className={houseModeStyle['count-label']}>逾期：</span>{sum.overdue_count}套</p>
                                <p><span className={houseModeStyle['count-label']}>欠费：</span>{sum.arrears_count}套</p>
                                <p><span className={houseModeStyle['count-label']}>分期：</span>{sum.stages_count}套</p>
                                <p><span className={houseModeStyle['count-label']}>亏损：</span>{sum.loss_count}套</p>
                                <p><span className={houseModeStyle['count-label']}>空置：</span>{sum.vacant_count}套</p>
                            </div>
                            <div className={houseModeStyle['count-item-group']}>
                                <p><span className={houseModeStyle['count-label']}>欠租：</span>{sum.overdue_rent / 100}元</p>
                                <p><span className={houseModeStyle['count-label']}>欠费：</span>{sum.arrears_money / 100}元</p>
                                <p><span className={houseModeStyle['count-label']}>智能锁：</span>{sum.lock_count}把</p>
                            </div>
                        </div>
                    </div>
                </div>
            </ContentLayout>
        );
    }
}

export default HouseMode;